package fifth.dao.impl;


import fifth.dao.StudentDao;
import fifth.domain.Student;
import fifth.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class StudentDaoImpl implements StudentDao {
    @Override
    public List<Student> findByPage(Integer pageNum, Integer pageSize) {
        // limit 0,10  limit 10,10  limit 20,10   limit 30,10   (pageNum-1)*pageSize ,pageSize
        try {
            QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
            return qr.query("select * from student order by studentNo limit ?,?", new BeanListHandler<Student>(Student.class),(pageNum-1)*pageSize,pageSize);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public long getCount() {
        try {
            QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
            return qr.query("select count(*) from student", new ScalarHandler<>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void add(Student stu) {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        try {
            qr.update("insert into student values(?,?,?,?,?)", stu.getStudentNo(),stu.getLoginPwd(),stu.getStudentName(),stu.getSex(),stu.getBornDate());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
